'use client'
import { useState, useEffect } from 'react'
import { Swiper, SwiperSlide } from 'swiper/react'
import { Autoplay } from 'swiper/modules'
import type { Swiper as SwiperType } from 'swiper'
import Image from 'next/image'

import 'swiper/css'

interface CustomPaginationProps {
  totalSlides: number
  activeIndex: number
  onSlideChange: (index: number) => void
}

const CustomPagination = ({ totalSlides, activeIndex, onSlideChange }: CustomPaginationProps) => {
  return (
    <div className="absolute bottom-24 left-1/2 z-10 flex -translate-x-1/2 transform space-x-6">
      {[...Array(totalSlides)].map((_, index) => (
        <div
          key={index}
          className={`h-3 w-3 rounded-full transition-all duration-300 ${index === activeIndex ? 'bg-red-500 opacity-60' : 'bg-gray-300'}`}
          onMouseEnter={() => onSlideChange(index)}
        />
      ))}
    </div>
  )
}

interface CarouselProps {
  images: string[]
}

const SwiperCarousel = ({ images }: CarouselProps) => {
  const [activeIndex, setActiveIndex] = useState(0)
  const [swiper, setSwiper] = useState<SwiperType | null>(null)

  const handleSlideChange = (swiper: SwiperType) => {
    setActiveIndex(swiper.realIndex)
  }

  const handlePaginationClick = (index: number) => {
    if (swiper) {
      swiper.slideToLoop(index)
    }
  }

  useEffect(() => {
    if (swiper) {
      swiper.on('slideChange', handleSlideChange)
    }
    return () => {
      if (swiper) {
        swiper.off('slideChange', handleSlideChange)
      }
    }
  }, [swiper])

  return (
    <div className="relative h-full">
      <Swiper
        modules={[Autoplay]}
        spaceBetween={30}
        slidesPerView={1}
        loop={true}
        autoplay={{ delay: 3000, disableOnInteraction: false }}
        onSwiper={setSwiper}
        className="h-full"
      >
        {images.map((image, index) => (
          <SwiperSlide key={index}>
            <Image src={image} alt={`Slide ${index + 1}`} fill priority />
          </SwiperSlide>
        ))}
      </Swiper>
      <CustomPagination totalSlides={images.length} activeIndex={activeIndex} onSlideChange={handlePaginationClick} />
    </div>
  )
}

export default SwiperCarousel
